package org.example.common.dubbo.router;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.tag.TagRouter;
import org.example.common.core.constants.GrayConstant;
import org.example.common.core.utils.ribbon.GrayRequestContextHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * 灰度路由
 */
public class GrayScaleRouter extends TagRouter {

    public GrayScaleRouter(URL url) {
        super(url);
    }

    @Override
    public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
        Boolean grayTag = GrayRequestContextHandler.getGrayTag();
        //灰度发布的服务
        List<Invoker<T>> grayServerList = new ArrayList<>();
        //正常的服务
        List<Invoker<T>> normalServerList = new ArrayList<>();
        invokers.forEach(invoker->{
            if(invoker.getUrl().getParameters().containsKey(GrayConstant.GRAY_HEADER)&&
                    invoker.getUrl().getParameter(GrayConstant.GRAY_HEADER).equals(GrayConstant.GRAY_VALUE)){
                grayServerList.add(invoker);
            }else{
                normalServerList.add(invoker);
            }
        });
        if (grayTag&&grayServerList.size()>0) {
            return grayServerList;
        }
        return normalServerList;
    }
}
